//
//  MYGEditMyReportsVC.swift
//  MYDoctor
//
//  Created by Denny on 2024/5/7.
//

import UIKit

class MYGEditMyReportsVC: MYGBaseController {
    var dataSource = [MYGArticleModel]()
    var from = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的报道"
        let rightBar:UIBarButtonItem = UIBarButtonItem(customView: rightItemBtn)
        self.navigationItem.rightBarButtonItem = rightBar
        initUI()
        hideBottomView()
        getTopData()
        getList()
    }
    
    func initUI(){
        view.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.left.top.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(30)
        }
        view.addSubview(topShowView)
        topShowView.snp.makeConstraints { make in
            make.top.equalTo(searchTextField.snp.bottom).offset(20)
            make.left.right.equalToSuperview()
            make.height.equalTo(21)
        }
        view.addSubview(deleteBtn)
        deleteBtn.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-bottomSafeheight)
            make.width.equalTo(141)
            make.height.equalTo(49)
            make.left.equalToSuperview()
        }
        view.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-bottomSafeheight)
            make.height.equalTo(49)
            make.right.equalToSuperview()
            make.left.equalTo(deleteBtn.snp.right)
        }
        view.addSubview(reportTable)
        reportTable.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(addBtn.snp.top)
            make.top.equalTo(topShowView.snp.bottom)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
            self.addBtn.addCAGradientLayerColor(colors: [UIColor.init(hexString: "#97B3FF").cgColor,
                                                         UIColor.init(hexString: "#4975EC").cgColor],
                                                startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint.init(x: 1, y: 0))
        })
        
    }
    
    func getTopData() {
        let parms = ["type": "2"]
        MYGNetwork<MYGMeAPI, MYGArticleFromModel>.request(target: .articleNewsFromList(param: parms)) {[weak self] item in
            self?.topShowView.configTopScrollView(item)
            MYGLoading.hide()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func getList() {
        MYGLoading.show()
        let parms = ["title":self.searchTextField.text ?? "","type": "2","from":from]
        MYGNetwork<MYGMeAPI, MYGPageModel<MYGArticleModel>>.request(target: .articleList(param: parms)) { item in
            self.dataSource = item.list
            self.reportTable.reloadData()
            MYGLoading.hide()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
     lazy var topShowView: ReportTopScrollView = {
        let control = ReportTopScrollView()
        control.tapIndexCompletion = {[weak self] from in
            self?.from = from
            self?.getList()
        }

        return control
    }()
    
    private lazy var rightItemBtn:UIButton = {
        let cont = UIButton()
        cont.setTitle("选择", for: .normal)
        cont.titleLabel?.font = .regular(13)
        cont.setTitleColor(.rgba(69, 131, 250, 1), for: .normal)
        cont.addTarget(self, action: #selector(tapChoose), for: .touchUpInside)
        return cont
    }()
    private lazy var searchTextField: UITextField = {
        let tf = UITextField()
        tf.font = .regular(14)
        tf.textColor = .rgba(142, 142, 147, 1)
        tf.backgroundColor = .rgba(243, 243, 243, 1)
        tf.layer.masksToBounds = true
        tf.layer.cornerRadius = 15
        tf.attributedPlaceholder = NSMutableAttributedString.rz.colorfulConfer(confer: { confer in
            confer.image(UIImage(named: "Chat/search"))
            confer.text(" 搜索")?.font(.regular(14)).textColor(.rgba(142, 142, 147, 1))
        })
        tf.textAlignment = .center
        tf.addTarget(self, action: #selector(textValueChanged), for: .editingChanged)
        //tf.delegate = self
        return tf
    }()
    
    lazy var deleteBtn:UIButton = {
        let control = UIButton()
        control.setTitle("删除", for: .normal)
        control.backgroundColor = UIColor.init(hexString: "#EFEFEF")
        control.setTitleColor(UIColor.init(hexString: "#818181"), for: .normal)
        control.titleLabel?.font = .regular(17)
        control.addTarget(self, action: #selector(tapDeleReport), for: .touchUpInside)
        return control
    }()
    
    lazy var addBtn:UIButton = {
        let control = UIButton()
        control.setTitle("加入我的报道", for: .normal)
        control.backgroundColor = UIColor.init(hexString: "#4975EC")
        control.setTitleColor(.white, for: .normal)
        control.titleLabel?.font = .regular(17)
        control.addTarget(self, action: #selector(tapAddBtn), for: .touchUpInside)
        return control
    }()
    
    lazy var allChoseBtn:UIButton = {
        let control = UIButton()
        control.setImage(UIImage.init(named: "MYG_report_boxnormal"), for: .normal)
        control.setImage(UIImage.init(named: "MYG_report_boxselected"), for: .selected)
        control.setImage(UIImage.init(named: "MYG_report_boxselected"), for: .highlighted)
        control.setTitle("全选", for: .normal)
        control.titleLabel?.font = .regular(13)
        control.setTitleColor(UIColor.init(hexString: "#4583FA"), for: .normal)
        control.addTarget(self, action: #selector(tapAllChose), for: .touchUpInside)
        return control
    }()
    
    private lazy var reportTable:UITableView = {
        let tab = UITableView(frame: CGRectZero, style: .plain)
        tab.delegate = self
        tab.backgroundColor = .clear
        tab.dataSource = self
        tab.register(cellWithClass: MYGMyReportsNewTableViewCell.self)
        tab.separatorStyle = .none
        tab.allowsMultipleSelectionDuringEditing = true
        return tab
    }()
    
    @objc func tapChoose() {
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.allChoseBtn)
        self.dataSource = self.dataSource.map({ obj in
            var result = obj
            result.isSelected = false
            result.isEdit = true
            return result
        })
        self.reportTable.reloadData()
        hideBottomView(false)
    }
    
    @objc func textValueChanged(){
        getList()
    }
    
    func hideBottomView(_ hide:Bool = true) {
        let hheight = hide ? 0: 49
        self.addBtn.snp.updateConstraints { make in
            make.height.equalTo(hheight)
        }
        self.deleteBtn.snp.updateConstraints { make in
            make.height.equalTo(hheight)
        }
        self.addBtn.isHidden = hide
        self.deleteBtn.isHidden = hide
    }
    
    @objc func tapAllChose() {
        self.allChoseBtn.isSelected = true
        self.dataSource = self.dataSource.map({ obj in
            var result = obj
            result.isSelected = true
            return result
        })
        self.reportTable.reloadData()
    }
    
    @objc func tapDeleReport() {
        var ids = [String]()
        let result = self.dataSource.filter { model in
            return model.isSelected
        }
        for(_,obj) in result.enumerated() {
            ids.append("\(obj.id)")
        }
        if ids.count == 0 {return}
        toDelete(ids)
    }
    
    func toDelete(_ ids:[String]) {
        let idstring = ids.joined(separator: ",")
        let parms = ["ids":idstring]
        MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGPageModel<MYGArticleModel>>.request(target: .deleteArticle(param: parms)) {[weak self] item in
            MYGLoading.hide()
            self?.getList()
            NotificationCenter.default.post(name: Notification.Name("MYGMyReportsNewViewController_getList"), object: nil)
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    @objc func tapAddBtn() {
        var ids = [String]()
        let result = self.dataSource.filter { model in
            return model.isSelected
        }
        for(_,obj) in result.enumerated() {
            ids.append("\(obj.id)")
        }
        if ids.count == 0 {return}
        toAdd(ids)
    }
    
    func toAdd(_ ids:[String]) {
        let idstring = ids.joined(separator: ",")
        let parms = ["ids":idstring]
        MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGPageModel<MYGArticleModel>>.request(target: .addArticle(param: parms)) {[weak self] item in
            MYGLoading.hide()
            self?.getList()
            NotificationCenter.default.post(name: Notification.Name("MYGMyReportsNewViewController_getList"), object: nil)
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
}

extension MYGEditMyReportsVC:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 127.5
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MYGMyReportsNewTableViewCell", for: indexPath) as! MYGMyReportsNewTableViewCell
        cell.selectionStyle = .none
        cell.tapBoxCompletion = {[weak self] data in
            guard let `self` = self else {return}
            self.dataSource = self.dataSource.map({ mode in
                var result = mode
                if result.id == data.id {
                    result.isSelected = !result.isSelected
                }
                return result
            })
            self.reportTable.reloadData()
        }
        if self.dataSource.count > 0 {
            let model = self.dataSource[indexPath.row]
            cell.model = model
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let unbind = UIContextualAction(style: .normal, title: "删除") {[weak self]
            (action, view, completionHandler) in
            guard let `self` = self else {return}
            let data = self.dataSource[indexPath.row]
            let ids = ["\(data.id)"]
            self.toDelete(ids)
            completionHandler(true)
        }
        unbind.backgroundColor = UIColor.init(hexString: "#FF0000")
        
        //创建“授权”事件按钮
        let authorize = UIContextualAction(style: .normal, title: "加入报道") {[weak self]
            (action, view, completionHandler) in
            guard let `self` = self else {return}
            
            let data = self.dataSource[indexPath.row]
            let ids = ["\(data.id)"]
            self.toAdd(ids)
            completionHandler(true)
        }
        authorize.backgroundColor = UIColor.init(hexString: "#0045FF")
        //返回所有的事件按钮 数组的第0个元素在最右边
        let configuration = UISwipeActionsConfiguration(actions: [authorize, unbind])
        return configuration
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.dataSource[indexPath.row]
        let vc = MYGMyReportDetailViewController()
        vc.id = "\(model.id)"
        self.navigationController?.pushViewController(vc)
    }
}

